﻿using Furion.VirtualFileServer;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FurStudy.Application
{
    public class PersonServices
    {
        private readonly IFileProvider _physicalFileProvide;
        private readonly IFileProvider _embeddedFileProvide;

        public PersonServices(Func<FileProviderTypes, object, IFileProvider> fileProviderResolve)
        {
            #region Func<FileProviderTypes, object, IFileProvider>方式

            // 解析物理文件系统
            _physicalFileProvide = fileProviderResolve(FileProviderTypes.Physical, @"c:/test");
            // 解析嵌入资源文件系统
            _embeddedFileProvide = fileProviderResolve(FileProviderTypes.Embedded, Assembly.GetEntryAssembly());

            #endregion

            #region FS静态类方式

            // 解析物理文件系统
            var physicalFileProvider = FS.GetPhysicalFileProvider(@"c:/test");

            // 解析嵌入资源文件系统
            var embeddedFileProvider = FS.GetEmbeddedFileProvider(Assembly.GetEntryAssembly());

            #endregion

        }

        #region IFileProvider常见操作

        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <returns></returns>
        public async Task ReadFileContent()
        {
            byte[] buffer;
            using (Stream readStream = _physicalFileProvide.GetFileInfo("文件路径").CreateReadStream())
            {
                buffer = new byte[readStream.Length];
                await readStream.ReadAsync(buffer.AsMemory(0, buffer.Length));
            }

            // 读取文件内容
            var content = Encoding.UTF8.GetString(buffer);
        }

        /// <summary>
        /// 获取文件目录内容(需递归查找)
        /// </summary>
        public void GetFileDirectoryContent()
        {
            var rootPath = "当前目录路径";
            var fileInfos = _physicalFileProvide.GetDirectoryContents(rootPath);
            foreach (var fileInfo in fileInfos)
            {
                if (fileInfo.IsDirectory)
                {
                    // 这里是递归
                }
            }
        }

        /// <summary>
        /// 监听文件变化
        /// </summary>
        public void ListeningFileChanges()
        {
            ChangeToken.OnChange(() => _physicalFileProvide.Watch("监听的文件"), () => 
            {
                // 这里写具体的逻辑
            });
        }

        #endregion
    }
}
